#coding=utf-8
from framework.db.mysql import BaseDb
from tornado import gen
from lib import log

class Menu(BaseDb):

    @gen.coroutine
    def insert_menu(self, menu_info):
        ret = yield self.insert("tb_food", menu_info)
        self.commit()

        raise gen.Return(ret)

    @gen.coroutine
    def select_menu(self, school_id, page, offset):
        sql = '''SELECT a.Fid, a.Fname, a.Fcanteen_id, a.Fschool_id, a.Fprice
                , a.Fimg, a.Fdesc, a.Fcreate_time
                FROM tb_food a 
                WHERE a.Fschool_id = %s 
                LIMIT %s, %s'''
        count_sql = 'SELECT count(a.Fid) FROM tb_food a WHERE a.Fschool_id = %s'

        ret = yield self.executejson(sql, (school_id, page, offset))
        count = yield self.execute(count_sql, (school_id))

        raise gen.Return((ret, count[0][0]))

    @gen.coroutine
    def find_menu(self, Fid):
        sql = '''SELECT Fid, Fname, Fcanteen_id, Fschool_id, Fprice
                , Fimg, Fdesc, Fcreate_time
                FROM tb_food 
                WHERE Fid = %s '''

        ret = yield self.executejson(sql, (Fid))

        if len(ret) >= 1:
            raise gen.Return(ret[0])
        else:
            raise gen.Return({})

    @gen.coroutine
    def del_menu(self, Fid):
        sql = 'DELETE FROM tb_food WHERE Fid = %s'

        ret = yield self.upsert_commit(sql, (Fid))

        raise gen.Return(ret)

    @gen.coroutine
    def update_menu(self, Fid, arg):
        menu_sql = '''UPDATE tb_food SET %s WHERE Fid = %s'''

        update_data = ''
        for i in arg.keys():
            update_data += i + '=%s,'

        menu_sql = menu_sql % (update_data[0:-1], '%s')

        data = arg.values()
        data.append(Fid)

        ret = yield self.upsert(menu_sql, tuple(data))

        self.commit()

        raise gen.Return(ret)